local Config = require("Config")
local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local Msg = require("core.Msg")
local Human = require("core.Human")

local DBUpdate = {_id=nil}

db = db or {
	isOpen = nil,
}
 
function init()
	LuaMongo.find(DB.db_open_middle)		
	if not LuaMongo.next(db) then
		LuaMongo.insert(DB.db_open_middle, db)
	end
end

function setMiddleOpenMsg()
	local msgRet = Msg.gc.GC_MIDDLE_IS_OPEN
	msgRet.isOpen = 0
	msgRet.isMiddle = 0
	if db.isOpen == true then
		msgRet.isOpen = 1
	end
	if Config.IS_MIDDLE then
		msgRet.isOpen = 1
		msgRet.isMiddle = 1
	end
end

function sendMiddleOpenMsg(human)
	setMiddleOpenMsg()
	Msg.send(Msg.gc.GC_MIDDLE_IS_OPEN, human.fd)
end

function setMiddleOpen(value)
	DBUpdate._id = db._id
	db.isOpen = value
	LuaMongo.update(DB.db_open_middle, DBUpdate, db)
	
	setMiddleOpenMsg()	
	for k, v in pairs(Human.onlineUuid) do	
		Msg.send(Msg.gc.GC_MIDDLE_IS_OPEN, v.fd)
	end
end

function isMiddleOpen()
	if db.isOpen == true then return true end
end

init()